﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Security.AccessControl;
using System.Text;

namespace Skylabs.Breeze
{
    public class FileTransfer : IEquatable<FileTransfer>,IEquatable<String>
    {
        public string LocalFileName { get; set; }
        public string FileName { get; set; }
        public long TotalSize { get; set; }
        public string Hash { get; set; }
        public bool CreatedBlankFile = false;
        public FileStream File;
        public int TotalPacketsReceived = 0;
        public long TotalBytesReceived { get; private set; }
        public int Progress { get; private set; }
        public FileTransfer(string fname,long size, string hash)
        {
            FileName = fname;
            TotalSize = size;
            Program.ServerTrace.TraceInformation("Starting file transfer");
            string path = Environment.ExpandEnvironmentVariables(Skylabs.Breeze.Properties.Settings.Default.dod);
            path = System.IO.Path.Combine(path, fname);
            Program.ServerTrace.TraceInformation("FileName:{0}\nSize:{1}\nLocalPath:{2}", fname, size.ToString(), path);
            Hash = hash;
            //File = MemoryMappedFile.CreateFromFile(path, FileMode.Create, fname, size,MemoryMappedFileAccess.ReadWrite);
            File = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            File.Seek(TotalSize - 1, SeekOrigin.Begin);
            TotalBytesReceived = 0;
            Progress = 0;
        }
        public void AddPart(long position,int length,byte[] data)
        {
            lock (this)
            {
                File.Seek(position, SeekOrigin.Begin);
                File.Write(data,0,length);
                File.Flush();
                TotalPacketsReceived++;
                TotalBytesReceived += length;
                Progress = (int)((TotalBytesReceived / TotalSize) * 100);
                if (TotalBytesReceived == TotalSize)
                {
                    try
                    {
                        File.Close();
                        File.Dispose();
                    }
                    catch (Exception e)
                    {
                        Program.ServerTrace.TraceEvent(TraceEventType.Error, 0, e.Message);
                    }
                    Program.ServerTrace.TraceInformation("File {0} complete\nPackets Received: {1}", LocalFileName,TotalPacketsReceived);
                }
            }
        }

        public bool Equals(FileTransfer other)
        {
            return other.FileName.Equals(FileName);
        }

        public bool Equals(string other)
        {
            return other.Equals(FileName);
        }
    }
}
